/** @jsxImportSource @emotion/react */
import * as React from "react";
import {InspectRecordLayout, InternalItemProps, OriginalViewProps, useItemInputControl} from "../../common/base";
import {
  PartName, Instrument, Passage, Sensitivity, Evaluation, Schematic, Spectrum, itemA检示意, itemA衍图谱, checkConfig部件, checkConfig仪器, checkConfig灵敏
} from "./orcBase";
import {assertNamesUnique, createItem, EditorAreaConfig} from "../../common/eHelper";
import {useRecordListSubX} from "../../hook/useRecordListSub";
import {EditStorageContext} from "../../StorageContext";
import {Button, Text, TextArea, useToast} from "customize-easy-ui-component";
import {useMedia} from "use-media";

export const OriginalView=
    React.forwardRef((
        { action: modAction,  verId, repId='', inp, rep}:OriginalViewProps, ref
    ) => {
      const {storage, setStorage} =React.useContext(EditStorageContext) as any;
      const { _TOFD_TS: SubRepIds }=storage;
      if(undefined===SubRepIds)
        return <div>请先确定网络和服务器是正常的。然后才考虑是否要做：
          <Button intent='danger' onPress={() => setStorage({...storage, _TOFD_TS: [] }) }>
            还没有数据！立刻初始化</Button></div>;
      //再一次确认，不能去掉：：避免hook报错, 分项报告模板的：【有可能】出现错，否则也没必要拆分两个组件做嵌套
      return <OriginalViewInner ref={ref} action={modAction} verId={verId} repId={repId} rep={rep}/>
  } );

/**为了解决useProjectListAs({count: refCount } )因为变动{前面storage数据{有TOFD_TS没有THICK_MS}和后面storage{有THICK_MS}数据不一样的}，导致hook报错！
 * 只好拆分成2层次嵌套拼装的俩组件了。父组件可以逻辑return子组件可用hook，不违反hook规则不报错。
 * */
const OriginalViewInner=
    React.forwardRef((
        { action: modAction,  verId, repId='', rep}:OriginalViewProps, ref
    ) => {
        //如何区分多个同一种类型分项报告的：
      const titleRender = (store: any) => {
        const firstTag=store?.部件名称;
        return <> { `[${firstTag}] `} </>;
      }
      const {list}=useRecordListSubX(ref,rep,repId,recordPrintList,modAction,verId,'TOFD_TS',titleRender);
      return <React.Fragment>
        {list}
      </React.Fragment>;
  } );


/**【特殊点】对于可重复分项框架模式的：表格调整setStorage({ _tblFixed: 必须点击“全部项目一起确认”才能立刻更新表格各列的宽度，需要多个按钮的点击，主报告的不需要;
 * 可重复分项框架模式需改成  JSON.parse(parentOrc?._tblFixed??'[]')   【工具】
 * */
const EntranceSetup =
    React.forwardRef((
        {children, show, alone = true, repId, verId, rep}: InternalItemProps, ref
    ) => {
      const atPrint = useMedia('print');
      const toast = useToast();
      const doCheckNames = React.useCallback((verId: string) => {
        //【承压更少项目】，那些属于公共模板目录的 分项报告的唯一性检查在对方自己检查看。
        const result = assertNamesUnique([{value: rep?.tzFields},
          {value: checkConfig部件, type:'s2Lu'},  {value: checkConfig仪器, type:'s2Lu'},
          {value: checkConfig灵敏, type:'s2Lu'},
          {value:[...itemA检示意, ...itemA衍图谱 ]},
          {value:['Projects','通道表','评定表' ]} ]);
        toast({title: "完成！", subtitle: result ? "没发现冲突" : "测试开关没开", intent: "success"});
      }, [rep,toast]);
      const {storage, setStorage} =React.useContext(EditStorageContext) as any;
      const getInpFilter = React.useCallback((par: any) => {
        const {_tblFixed, } =par||{};
        return {_tblFixed, };
      }, []);
      const {inp, setInp} = useItemInputControl({ref});
      if (atPrint) return null;
      else return (
          <InspectRecordLayout inp={inp} setInp={setInp} getInpFilter={getInpFilter} show={show}
                               alone={alone} label={'初始化本报告，默认值配置等'}>
            {process.env.REACT_APP_TEST==='true' && <><div>
              <Text variant="h5">构建开发模板时的工具：校验模板的存储name冲突；</Text>
              <Button intent='primary' onPress={() => doCheckNames(verId!)}>校验模板name唯一性</Button>
              <Text variant="h5">设置待测试表格的各列宽度：</Text>
              <TextArea value={storage?._tblFixed || ''} rows={2} onChange={e =>{
                JSON.parse(e.currentTarget.value??'[]');
                setStorage({ ...storage, _tblFixed: e.currentTarget.value || undefined}); }}/>
            </div></>
            }
            <hr/>
          </InspectRecordLayout>
      );
  });


const recordPrintList = [
  createItem('Entrance', <EntranceSetup/>),
  createItem('PartName', <PartName/>),
  createItem('Instrument', <Instrument/>),
  createItem('Passage', <Passage/>),
  createItem('Sensitivity', <Sensitivity/>),
  createItem('Evaluation', <Evaluation/>),
  createItem('Schematic', <Schematic/>),
  createItem('Spectrum', <Spectrum/>),
] as EditorAreaConfig[];
